<template>
	<view class="home-page" v-if="showIndexPage">
		<view class="top">
			<view class="title">
				<view class="title-name" style="display: none;">家长端</view>
				<view class="bell" @click="toPage"><van-icon name="/static/icon/bell.png" /></view>
			</view>
			<view v-if="!studentIsEmpt" class="sapce-heieght-60"></view>
			<Expire v-if="studentStore.isExpire && !studentIsEmpt"/>
			<UnboundDevice v-if="studentIsEmpt"/>
			<User v-if="!studentIsEmpt" @onSelectChange="onSelectChange"/>
		</view>
		<view class="main">
			<ChildPhoneStatus @refresPhoneStatus="() =>refreshHttp()" />
			<childDeviceStatus :childPhoneStatusInfo="childPhoneStatusInfo"/>
			<SwiperBanner :banner="banner"/>
			<RuleSetting />
			<Other />
			<Statistics title="今日使用时长统计(总时长)" :statisticsData="statisticsData" @sortByUseTime="sortByUseTime" :sort="des"/>
		</view>
		<!-- <GlobalWebsocketNotice /> -->
	</view>
	<view v-else class="loadingHomePage">
		<Loading />
	</view>
	<GoLogin v-if="notLogined" />
	<FirstLoginDialog @onOver="onOverhandler" v-if="firstlogin" :show="firstlogin"/>
	<!-- <GiveVip v-if="giveVipStatus" :show="giveVipStatus" @onDestroy="closeGiveVip"/> -->
		
	<!-- <XiaomiVieo v-if="true" :visible="true" des="您下载的孩子手机品牌为小米、红米手机，必须激活企业模式，否则无法正常管控!可以点击下方查看视频查看具体操作方法。" /> -->
	<!-- <XiaomiVieo v-if="true" :visible="true" des="您绑定的小孩手机为荣耀手机，需正确开启定位、设备管理器、无障碍三个权限，否则会影响管控效果！" /> -->
	<!-- <XiaomiVieo v-if="true" :visible="true" des="您绑定的小孩手机为小米手机，如提示孩子端未激活企业模式，请参考视频操作，否则无法正常管控！" /> -->
	<!-- <Receive v-if="receiveVisible" :visible="receiveVisible" :data="receiveData" @close="onCloseReceive" @jump="jumpage" @onOver="onOver"/> -->
	
</template>

<script setup lang="ts">
	import {ref, onMounted, computed} from 'vue'
	import {onShow, onLoad} from "@dcloudio/uni-app"
	import Expire from "./expire.vue"
	import UnboundDevice from "./unboundDevice.vue";
	import ChildPhoneStatus from "./childPhoneStatus.vue";
	import childDeviceStatus from "./childDeviceStatus.vue";
	// import GlobalWebsocketNotice from '@/components/globalWebsocketNotice/index.vue' // 进入首页，如果我分享连接后，朋友通过链接注册了，我会收到奖励
	import SwiperBanner from "./swiperBanner.vue";
	import RuleSetting from "./ruleSetting.vue";
	import Other from "./other.vue";
	import Statistics from "@/components/statistics/index.vue";
	import User from "./user.vue";
	import GoLogin from "@/components/goLogin/index.vue"
	import FirstLoginDialog from "@/components/firstLoginDialog/index.vue"
	// import GiveVip from "@/components/giveVip/index.vue"
	import Loading from "@/components/loading.vue"


	
	import { homeServer } from "@/common/index";
	import { useStudentListStore } from "@/stores/useStudentList.js"
	import { useVipStore} from "@/stores/useVip.js"
		
	import { useBound } from "@/hooks/useBound.ts"
	import {useParentInfo} from '@/stores/useParentInfo.js'
	import {  onPullDownRefresh, onReachBottom } from "@dcloudio/uni-app";
	import { urlHelp } from '@/utils/index';
	import { global, mock } from "@/utils/index"
	
	// import websocket from '@/utils/ws.js';
	// import { WEBSOCKET } from "@/utils/constant.js"
	
	

	const vipStore = useVipStore()
	const {tipBoundStudent, studentIsEmpt} = useBound();
	const studentStore = useStudentListStore();
	const parentStore = useParentInfo();
	const curStd = computed(() => studentStore.currentStudent);
	
	const notLogined = computed(() => !mock.isLogged())
	
	
	const receiveVisible = ref(true)
	const receiveData = ref({
		completeContent: '您的好友150****1111家长端注册成功',
		popupName:"首次分享获得",
		worth: 5,
		first:"2天vip和10积分"
	})
	const onCloseReceive =() => {
		receiveVisible.value = false
	}
	const jumpage = () => {
		uni.navigateTo({
			url:"/pagesD/jackpot/index"
		})
	}
	const onOver = () => {
		console.log("无论是关闭还是跳转都需要销毁这个ws的id")
	}

	
	const showIndexPage = ref(false);
	const firstlogin = ref(false)
	const giveVipStatus = ref(false)
	const onOverhandler = () => {
		firstlogin.value = false
	}
	const closeGiveVip = () => {
		giveVipStatus.value = false
	}
	const onshowGiveVip = () => {
		const fromPage = uni.getStorageSync('fromPage')
		if(fromPage === "addChildDevices"){ // 来自添加孩子设备
			giveVipStatus.value = true
			uni.removeStorageSync('fromPage')
		}
	}
	
	const connectWS = async () => {
		const userInfo = global.syncGetUerInfoByLocal()
		if(userInfo?.memberId){
			// console.log("首页链接ws", `${WEBSOCKET}${userInfo.memberId}`)
			// websocket.connectWebSocket(`${WEBSOCKET}${userInfo.memberId}`)
			// const retry = () => {
			// 	console.log("这是重连", `${WEBSOCKET}${userInfo.memberId}`)
			// 	websocket.connectWebSocket(`${WEBSOCKET}${userInfo.memberId}`)
			// 	uni.$on("wxConnectStatus", (status) => {
			// 		console.log("是否连接成功", status)
			// 	})
			// }
		 //   websocket.closeWebSocket({mode:'againConnect', reconnect: retry}) // 先关闭之前的ws，再次重新连接
		}
	}
	
	
	
	const queryLoginCount = () => {
		const userInfo = global.syncGetUerInfoByLocal()
		console.log('第一次登录弹窗', userInfo?.firstLogin,  global.getFirstLogin())
		if(userInfo && userInfo?.firstLogin && mock.isLogged() && global.getFirstLogin() === ""){ // true： 首次登录（需要一个弹窗） false： 不是首次登录 （不需要弹窗）
			firstlogin.value = true
			const newUserInfo = {
				...userInfo,
				firstLogin: false
			};
			global.saveUserInfoToLocal(newUserInfo)
			// uni.showModal({
			// 	title:"",
			// 	success() {
			// 		global.saveFirstLogin()
			// 	},
			// 	content:"管手机旨在防止青少年沉迷手机帮助孩子从他律走向自律，继而走向成才，走向成功！安装本软件前，应与孩子充分沟通，使其了解和接受本软件。本软件尊重和保护未成年人隐私，不远程截屏、录音、拍摄，不搜集通话、短信、聊天记录。"
			// })
		}
	}
			


	// 刷新设备
	const refreshHttp = async () => {
		if(vipStore.isOutTime()){
			uni.showToast({
				title:"请稍后再刷新",
				icon: 'none'
			})
		} else {
			getStudentStatus(true)
		}
	}


	const queryIsExpire = (expireTimeStamp: number): boolean =>{
		return Date.now() >= expireTimeStamp
	}
	
	const toPage = () => {
		// todo 暂时不需要这个通知功能
		return;
		// if(studentIsEmpt.value){
		// 	tipBoundStudent();
		// 	return;
		// }
		// uni.navigateTo({
		// 	url:'/pagesA/message/index'
		// })
	}
	
	// 切换了学生，此时需要重新请求数据
	const onSelectChange = async () => {
		showIndexPage.value = false;
		await getStudentStatus();
		await statistics();
		showIndexPage.value = true;
	}
	onShow( async () => {
		// showIndexPage.value = false;
		// await getStudentStatus();
		// await statistics();
		// showIndexPage.value = true;
		onshowGiveVip()
		queryLoginCount()
		// connectWS()
		studentList();
		getMemberInfo();		
		getBannerImage();
	})
	const sutdents = ref([]);
	// 获取学生信息
	const studentList = async () => {
		try{
			const {data, status} = await homeServer.studentList()
			if(status === "200"){
				const sts = data?.map(item => urlHelp.imgAddPrefix(item, 'imageUrl')) || [];
				sutdents.value = sts
				studentStore.setStudents(sts || []);
				if(sts && Array.isArray(sts) && sts.length){
					if(!studentStore.currentStudent?.id){ // 没有选中过孩子，这里用第一个孩子，作为默认孩子
					console.log('第一个孩子', sts[0])
						studentStore.onselectStudent(sts[0]); // 默认展示第一个孩子
					}
					getStudentStatus(); // 孩子手机状态
					statistics(); // 今日统计
					const expireTimeStamp = sts?.[0]?.['expireTimeStamp']
					if(expireTimeStamp){
						const bool = queryIsExpire(Number(expireTimeStamp));
						studentStore.setIsExpire(bool)
					}
				}
				if(data?.length === 0 || !Array.isArray(data)){
					studentStore.setStudents([]);
					studentStore.onselectStudent({}); // 默认展示第一个孩子
					getStudentStatus(); // 孩子手机状态
					statistics(); // 今日统计
				}
			}
			showIndexPage.value = true
		}catch(e){
			showIndexPage.value = true
			console.log(e)
			//TODO handle the exception
		}
	}
	// 获取家长信息
	const getMemberInfo = async () => {
		try{
			const {status,data} = await homeServer.getMemberInfo()
			if(status === '200'){
				parentStore.setParentInfo(data);
			}
		}catch(e){
			console.log(e)
			//TODO handle the exception
		}
	}

	const deviceStatus =  {
	 	deviceStatus: "-", // 管控状态 0:无管控信号 1:管控 2:脱管
	 	electricQuantity:"-", // 电池电量0-100 -1:未知
	 	screenStatus:"-", //屏幕状态 0:屏幕关闭 1:屏幕开启 2:未知
		studentId:"",
	 	whetherOnline:"-", // 	是否在线 0:离线 1:在线 2:未知
	 }
	const defaultPhoneStatus = mock.isLogged() ? deviceStatus : mock.PhoneStatus.data
	
	const childPhoneStatusInfo = ref(defaultPhoneStatus)
	// 获取获取孩子手机状态
	const getStudentStatus = async (isRefresh = false) => {
		if(curStd.value?.id){
			try{
				const { status, data} = await homeServer.getStudentStatus({studentId: curStd.value?.id})
				if(status === '200'){
					childPhoneStatusInfo.value = data;
					if(isRefresh){
						uni.showToast({
							title:"刷新设备成功",
							icon:"none"
						})
					}
				}
			}catch(e){
				//TODO handle the exception
			}
		} else {
			childPhoneStatusInfo.value = defaultPhoneStatus;
			studentStore.setStudents([]);
			studentStore.onselectStudent({}); // 默认展示第一个孩子
			console.log('没找到学生id', curStd.value)
		}
	}
	
	// 获取banner图
	const banner = ref([]);
	const getBannerImage = async () => {
		try{
			const {status, data} = await homeServer.getBannerImage();
			if(status === "200"){
				console.log('banner', data)
				if(data?.length === 0){
					banner.value = [{
						image:"/static/icon/banner.jpg",
						isShow: true,
						skipAddress:"/pages/tabbar/home/index",
						url:"/pages/tabbar/home/index"
					}]
				}  else {
					banner.value = data;
				}
			}
		}catch(e){
			console.log(e)
			//TODO handle the exception
		}
	}
	

	
	// 今日统计
	const statis = mock.isLogged() ? [] : JSON.parse(JSON.stringify(mock.INDEX_APP_USE_INFO.data)).map(item =>urlHelp.imgAddPrefix(item, 'appImage'))
	const statisticsData = ref(statis);
	const statistics = async () => {
		// 模拟数据
		// const list = [{
		// 	appId:'',
		// 	appImage:"/static/images/tmp/bilibili.png",
		// 	appName:"哔哩哔哩",
		// 	packageName:"",
		// 	useCount:1,
		// 	useTime:86400
		// },~
		// {
		// 	appId:'',
		// 	appImage:"/static/images/tmp/bilibili.png",
		// 	appName:"哔哩哔哩",
		// 	packageName:"",
		// 	useCount:1,
		// 	useTime:15000
		// },
		// {
		// 	appId:'',
		// 	appImage:"/static/images/tmp/bilibili.png",
		// 	appName:"哔哩哔哩",
		// 	packageName:"",
		// 	useCount:1,
		// 	useTime:43200
		// },
		// ];
		// statisticsData.value = addPercentageToArray(list)
		// return;
		if(curStd.value?.id){
			try{
				console.log('统计')
				const {status, data} = await homeServer.statistics({studentId:curStd.value?.id, type: 1})
				if(status === '200'){
					statisticsData.value = urlHelp.addPercentageToArray(data).map(item => urlHelp.imgAddPrefix(item, 'appImage'));
					console.log('statisticsData.value-->', statisticsData.value)
				} 
			}catch(e){
				console.log('统计接口出错', e)
				//TODO handle the exception
			}
		} else {
			console.log("未发现学生id")
		}
	};
	const sortByUseTime = () => {
		if(statisticsData.value.length === 0 || statisticsData.value.length == 1){
			return;
		}
		const useTime = 'useTime'
	    const cur_max_sort = statisticsData.value[0][useTime] > statisticsData.value[1][useTime]; 
		function sortArrayByUseTime(arr, ascending = true) {  
		    // ascending 参数默认为 true，表示从小到大排序  
		    // 如果设置为 false，则表示从大到小排序  
		    arr.sort((a, b) => {  
		        if (ascending) {  
		            // 从小到大排序  
		            return a.useTime - b.useTime;  
		        } else {  
		            // 从大到小排序  
		            return b.useTime - a.useTime;  
		        }  
		    });  
		    return arr;  
		}  
		if(cur_max_sort){ // 现在是从时间最大到最小排序的，那么需要反过来
			statisticsData.value = sortArrayByUseTime(statisticsData.value, true)
		} else {// 现在是从时间最小到最大排序的，那么需要反过来
			statisticsData.value = sortArrayByUseTime(statisticsData.value, false)
		}
		
	}
	onMounted(() => {	
		studentList();
		getMemberInfo();		
		getBannerImage();
	})


	//  下拉刷新
	onPullDownRefresh(() => {
		studentList();
		getMemberInfo();		
		getBannerImage();
		uni.stopPullDownRefresh();
	});
	
	//  触底加载
	onReachBottom(() => {
		// studentList();
		// getMemberInfo();		
		// getBannerImage();
		// uni.stopPullDownRefresh();
	});
		
		
</script>
<style lang="scss">
	page{
		// width: 100%;
		// height: 100%;
		// background-color: #36DD99;
	}
</style>
<style lang="scss" scoped>
	.loadingHomePage{
		background-color: rgba(0, 0, 0, 0.05);
		width: 100vw;
		height: 100vh;
		display: flex;
		justify-content: center;
		align-items: center;
	}
	.home-page{
		.sapce-heieght-60{
			height: 60upx;
		}
		.top{
			width: 100%;
			min-height: 240upx;
			background: linear-gradient( 180deg, #2BC888 0%, #36DD99 100%);
			border-radius: 0px 0px 0px 0px;
			padding-bottom: 20upx;
			.title{
				display: flex;
				align-items: center;
				justify-content: center;
				position: relative;
				padding-bottom: 30upx;
				.title-name{
					font-weight: 800;
					font-size: 18px;
					color: #FFFFFF;
				}
				.bell{
					position: absolute;
					right:20upx;
					visibility: hidden;
				}
			}
		}
		
		.main{
			min-height: 100%;
			background-color:#f7fbfe;
			border-top-left-radius: 60upx;
			border-top-right-radius: 60upx;
			// position: relative;
			// z-index: 100;
			// .main-top-bg{
			// 	width: 100%;
			// 	height: 60upx;
			// 	z-index: 101;
			// 	position: absolute;
			// 	top:0;
			// 	background: #2BC888;
			// }
			
			
		}
	}

</style>
